﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SilverlightParser.Web.Backend
{
    public class Market
    {
        public class JobQueue
        {
             public List<Job> InJobQueues=new List<Job>();
             public List<Job> OutJobQueues=new List<Job>();

        }
        SortedList<string, JobQueue> JobQueues = new SortedList<string, JobQueue>();

        public void PostJob(Job job)
        {
            List<Job> jobs = GetJobQueue(job.Contact, true).OutJobQueues;
            lock (jobs)
            {
                jobs.Add(job);
            }
        }

        JobQueue GetJobQueue(string clientid, bool ifnocreateone)
        {
            if (!JobQueues.ContainsKey(clientid))
            {
                if (ifnocreateone)
                {
                    JobQueue jobs = new JobQueue();
                    lock (this.JobQueues)
                    {
                        this.JobQueues.Add(clientid, jobs);
                    }
                    return jobs;
                }
                else
                    return null;
            }
            JobQueue existjobs = JobQueues[clientid];
            return existjobs;
        }
        public Job GetJob(string clientid)
        {
            JobQueue jq = GetJobQueue(clientid, false);
            if(jq==null)
                return null;
            List<Job> jobs = jq.OutJobQueues;
            if (jobs == null)
                return null;
            lock (jobs)
            {
                if (jobs.Count == 0)
                    return null;

                Job job = jobs[0];
                jobs.RemoveAt(0);
                return job;
            }
        }

        public void PostJobResult(Job job)
        {
            List<Job> jobs = GetJobQueue(job.Contact, true).InJobQueues;
            lock (jobs)
            {
                jobs.Add(job);
            }
        }

        /// <summary>
        /// Parser 端获取Silverlight端执行Job的结果
        /// </summary>
        /// <param name="clientid"></param>
        /// <returns></returns>
        public Job GetJobResult(string clientid)
        {
            JobQueue jq = GetJobQueue(clientid, false);
            if (jq == null)
                return null;
            List<Job> jobs = jq.InJobQueues;
            if (jobs == null)
                return null;
            lock (jobs)
            {
                if (jobs.Count == 0)
                    return null;

                Job job = jobs[0];
                jobs.RemoveAt(0);
                return job;
            }
        }
    }
}